<?php
/**
 * ****************************************************************************
 *  - TDMDownloads By TDM   - TEAM DEV MODULE FOR XOOPS
 *  - GNU Licence Copyright (c)  (www.xoops.org)
 *
 * La licence GNU GPL, garanti à l'utilisateur les droits suivants
 *
 * 1. La liberté d'exécuter le logiciel, pour n'importe quel usage,
 * 2. La liberté de l' étudier et de l'adapter à ses besoins,
 * 3. La liberté de redistribuer des copies,
 * 4. La liberté d'améliorer et de rendre publiques les modifications afin
 * que l'ensemble de la communauté en bénéficie.
 *
 * @copyright   http://www.tdmxoops.net
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
 * @author		TDM (G.Mage); TEAM DEV MODULE
 *
 * ****************************************************************************
 */

include 'admin_header.php';
//Affichage de la partie haute de l'administration de Xoops
xoops_cp_header();
//On recupere la valeur de l'argument op dans l'URL$
if (isset($_REQUEST['op'])) {
	$op = $_REQUEST['op'];
} else {
	$op = 'liste';
}
//paramètres:
// pour les images des téléchargement:
$uploaddir = XOOPS_ROOT_PATH . '/uploads/TDMDownloads/images/shots/';
$uploadurl = XOOPS_URL . '/uploads/TDMDownloads/images/shots/';
// pour les fichiers
$uploaddir_downloads = XOOPS_ROOT_PATH . '/uploads/TDMDownloads/downloads/';
$uploadurl_downloads = XOOPS_URL . '/uploads/TDMDownloads/downloads/';
/////////////

//appel des class
$downloadscat_Handler =& xoops_getModuleHandler('tdmdownloads_cat', 'TDMDownloads');
$downloads_Handler =& xoops_getModuleHandler('tdmdownloads_downloads', 'TDMDownloads');
$downloadsvotedata_Handler =& xoops_getModuleHandler('tdmdownloads_votedata', 'TDMDownloads');
$downloadsfield_Handler =& xoops_getModuleHandler('tdmdownloads_field', 'TDMDownloads');
$downloadsfielddata_Handler =& xoops_getModuleHandler('tdmdownloads_fielddata', 'TDMDownloads');
$downloadsbroken_Handler =& xoops_getModuleHandler('tdmdownloads_broken', 'TDMDownloads');

//appel du menu admin
if ( !is_readable(XOOPS_ROOT_PATH . "/Frameworks/art/functions.admin.php"))	{
    tdmdownloads_adminmenu(3, _MI_TDMDOWNLOADS_ADMENU3);
} else {
    include_once XOOPS_ROOT_PATH.'/Frameworks/art/functions.admin.php';
    loadModuleAdminMenu (3, _MI_TDMDOWNLOADS_ADMENU3);
}
// compte le nombre de téléchargement non validé
$criteria = new CriteriaCompo();
$criteria->add(new Criteria('status', 0));
$downloads_waiting = $downloads_Handler->getCount($criteria);
if (isset($_REQUEST['statut_display'])) {
    $statut_menu = 0;
}else{
    $statut_menu = 1;
}
// Sous-menu
echo '<div class="head" align="center">';
echo $op == 'new_downloads' ? _AM_TDMDOWNLOADS_DOWNLOADS_NEW : '<a href="downloads.php?op=new_downloads">' . _AM_TDMDOWNLOADS_DOWNLOADS_NEW . '</a>';
echo ' | ';
echo $op == 'liste' && $statut_menu == 1 ? _AM_TDMDOWNLOADS_DOWNLOADS_LISTE : '<a href="downloads.php?op=liste">' . _AM_TDMDOWNLOADS_DOWNLOADS_LISTE . '</a>';
echo ' | ';
echo $op == 'liste' && $statut_menu == 0 ? _AM_TDMDOWNLOADS_DOWNLOADS_WAIT . ($downloads_waiting == 0 ? '' : ' (<span style="color : Red">' . $downloads_waiting . '</span>)') : '<a href="downloads.php?op=liste&statut_display=0">' . _AM_TDMDOWNLOADS_DOWNLOADS_WAIT . ($downloads_waiting == 0 ? '' : ' (<span style="color : Red">' . $downloads_waiting . '</span>)').'</a>';
//echo ' | ';
//echo $op == 'search' ? _AM_TDMDOWNLOADS_DOWNLOADS_SEARCH : '<a href="downloads.php?op=search">' . _AM_TDMDOWNLOADS_DOWNLOADS_SEARCH . '</a>';

echo '</div><br>';

//Les valeurs de op qui vont permettre d'aller dans les differentes parties de la page
switch ($op) 
{
	// Vue liste
    case "liste":
    		//Parameters	
		$criteria = new CriteriaCompo();
		$numrowscat = $downloadscat_Handler->getCount();
        // redirection si il n'y a pas de catégories
		if ($numrowscat==0) {
			redirect_header('category.php?op=new_cat', 2, _AM_TDMDOWNLOADS_REDIRECT_NOCAT);
		}
		// affiche uniquement les téléchargements activés
		if (isset($_REQUEST['statut_display'])) {
			if ($_REQUEST['statut_display']==0){
				$criteria->add(new Criteria('status', 0));
				$statut_display = 0;
			}else{
				$criteria->add(new Criteria('status', 0, '!='));
				$statut_display = 1;
			}
		}else{
			$criteria->add(new Criteria('status', 0, '!='));
			$statut_display = 1;
		}
		$numrows = $downloads_Handler->getCount($criteria);
		if (isset($_REQUEST['limit'])) {
 			$criteria->setLimit($_REQUEST['limit']);
 			$limit = $_REQUEST['limit'];
 		} else {
 			$criteria->setLimit($xoopsModuleConfig['perpageadmin']);
 			$limit = $xoopsModuleConfig['perpageadmin'];
 		}
		if (isset($_REQUEST['start'])) {
			$criteria->setStart($_REQUEST['start']);
			$start = $_REQUEST['start'];
		} else {
			$criteria->setStart(0);
 			$start = 0;
 		}
		$document_tri = 1;
		$document_order = 1;
		if (isset($_REQUEST['document_tri'])) {
        	if ($_REQUEST['document_tri']==1){
				$criteria->setSort('date');
				$document_tri=1;
			}
			if ($_REQUEST['document_tri']==2){
				$criteria->setSort('title');
				$document_tri=2;
			}
			if ($_REQUEST['document_tri']==3){
				$criteria->setSort('hits');
				$document_tri=3;
			}
			if ($_REQUEST['document_tri']==4){
				$criteria->setSort('rating');
				$document_tri=4;
			}
            if ($_REQUEST['document_tri']==5){
				$criteria->setSort('cid');
				$document_tri=5;
			}
		} else {
			$criteria->setSort('date');
 		}
		if (isset($_REQUEST['document_order'])) {
			if ($_REQUEST['document_order']==1){
				$criteria->setOrder('DESC');
				$document_order=1;
			}
			if ($_REQUEST['document_order']==2){
				$criteria->setOrder('ASC');
				$document_order=2;
			}
		} else {
			$criteria->setOrder('DESC');
 		}		
		$downloads_arr = $downloads_Handler->getall( $criteria );
		if ( $numrows > $limit ) {
			$pagenav = new XoopsPageNav($numrows, $limit, $start, 'start', 'op=liste&limit=' . $limit . '&document_tri=' . $document_tri. '&document_order=' . $document_order . '&statut_display=' . $statut_display);
 			$pagenav = $pagenav->renderNav(4);
 		} else {
 			$pagenav = '';
 		}
		//Affichage du tableau des téléchargements
		if ($numrows>0) {
			echo '<div align="right"><form id="form_document_tri" name="form_document_tri" method="get" action="document.php">';
			echo _AM_TDMDOWNLOADS_TRIPAR . "<select name=\"document_tri\" id=\"document_tri\" onchange=\"location='".XOOPS_URL."/modules/".$xoopsModule->dirname()."/admin/downloads.php?statut_display=$statut_display&document_order=$document_order&document_tri='+this.options[this.selectedIndex].value\">";
			echo '<option value="1"' . ($document_tri == 1 ? ' selected="selected"' : '') . '>' . _AM_TDMDOWNLOADS_FORMDATE . '</option>';
			echo '<option value="2"' . ($document_tri == 2 ? ' selected="selected"' : '') . '>' . _AM_TDMDOWNLOADS_FORMTITLE . '</option>';
			echo '<option value="3"' . ($document_tri == 3 ? ' selected="selected"' : '') . '>' . _AM_TDMDOWNLOADS_FORMHITS . '</option>';
            echo '<option value="4"' . ($document_tri == 4 ? ' selected="selected"' : '') . '>' . _AM_TDMDOWNLOADS_FORMRATING . '</option>';
            echo '<option value="5"' . ($document_tri == 5 ? ' selected="selected"' : '') . '>' . _AM_TDMDOWNLOADS_FORMCAT . '</option>';
			echo '</select> ';
			echo _AM_TDMDOWNLOADS_ORDER . "<select name=\"order_tri\" id=\"order_tri\" onchange=\"location='".XOOPS_URL."/modules/".$xoopsModule->dirname()."/admin/downloads.php?statut_display=$statut_display&document_tri=$document_tri&document_order='+this.options[this.selectedIndex].value\">";
			echo '<option value="1"' . ($document_order == 1 ? ' selected="selected"' : '') . '>DESC</option>';
			echo '<option value="2"' . ($document_order == 2 ? ' selected="selected"' : '') . '>ASC</option>';
			echo '</select> ';
			echo '</form></div>';			
			echo '<table width="100%" cellspacing="1" class="outer">';
			echo '<tr>';
			echo '<th align="center" width="5%">'._AM_TDMDOWNLOADS_FORMFILE.'</th>';
			echo '<th align="center">' . _AM_TDMDOWNLOADS_FORMTITLE . '</th>';
			echo '<th align="center">' . _AM_TDMDOWNLOADS_FORMCAT . '</th>';
            echo '<th align="center" width="5%">' . _AM_TDMDOWNLOADS_FORMHITS . '</th>';
            echo '<th align="center" width="5%">' . _AM_TDMDOWNLOADS_FORMRATING . '</th>';
			echo '<th align="center" width="15%">'._AM_TDMDOWNLOADS_FORMACTION.'</th>';
			echo '</tr>';
			$class = 'odd';
			foreach (array_keys($downloads_arr) as $i) {
				$class = ($class == 'even') ? 'odd' : 'even';
                $downloads_lid = $downloads_arr[$i]->getVar('lid');
                $downloads_title = $downloads_arr[$i]->getVar('title');
                $downloads_category =& $downloadscat_Handler->get($downloads_arr[$i]->getVar('cid'));		
 				echo '<tr class="'.$class.'">';
				echo '<td align="center" width="10%">';
				echo '<a href="../visit.php?cid=' . $downloads_arr[$i]->getVar('cid') . '&lid=' . $downloads_lid . '" target="_blank"><img src="../images/icon/download.png" alt="Download ' . $downloads_title . '" title="Download ' . $downloads_title . '"></a>';
				echo '</td>';
                echo '<td align="center">' . $downloads_title . '</td>';
                echo '<td align="center">' . $downloads_category->getVar('title') . '</td>';
				echo '<td align="center">' . $downloads_arr[$i]->getVar('hits') . '</td>';
				echo '<td align="center">' . number_format($downloads_arr[$i]->getVar('rating'), 1) . '</td>';
								
				echo '<td align="center" width="15%">';
				echo ($statut_display == 1 ? '<a href="downloads.php?op=lock_status&downloads_lid=' . $downloads_lid . '"><img src="./../images/icon/lock.png" border="0" alt="' . _AM_TDMDOWNLOADS_FORMLOCK . '" title="' . _AM_TDMDOWNLOADS_FORMLOCK . '"></a> ' : '<a href="downloads.php?op=update_status&downloads_lid=' . $downloads_lid . '"><img src="./../images/icon/renew_mini.gif" border="0" alt="' . _AM_TDMDOWNLOADS_FORMVALID . '" title="' . _AM_TDMDOWNLOADS_FORMVALID . '"></a> ');
				echo '<a href="downloads.php?op=view_downloads&downloads_lid=' . $downloads_lid . '"><img src="../images/icon/view_mini.png" alt="' . _AM_TDMDOWNLOADS_FORMDISPLAY.'" title="' . _AM_TDMDOWNLOADS_FORMDISPLAY . '"></a> ';
                echo '<a href="downloads.php?op=edit_downloads&downloads_lid=' . $downloads_lid . '"><img src="../images/icon/edit_mini.gif" alt="' . _AM_TDMDOWNLOADS_FORMEDIT.'" title="' . _AM_TDMDOWNLOADS_FORMEDIT . '"></a> ';
                echo '<a href="downloads.php?op=del_downloads&downloads_lid=' . $downloads_lid . '"><img src="../images/icon/delete_mini.gif" alt="' . _AM_TDMDOWNLOADS_FORMDEL.'" title="' . _AM_TDMDOWNLOADS_FORMDEL . '"></a>';
				echo '</td>';
			 }
			 echo '</table><br />';
			 echo '<br /><div align=right>' . $pagenav . '</div><br />';
		}else{
            echo '<div class="errorMsg" style="text-align: center;">' . _AM_TDMDOWNLOADS_ERREUR_NODOWNLOADS . '</div>';
        }
    
	break;  
    
    // vue création
    case "new_downloads":
        //Affichage du formulaire de création des téléchargements
    	$obj =& $downloads_Handler->create();
    	$form = $obj->getForm($donnee = array(), false, true);
    	$form->display();
    break;
    
    // Pour éditer un téléchargement
    case "edit_downloads":
        //Affichage du formulaire de création des téléchargements
        $obj = $downloads_Handler->get($_REQUEST['downloads_lid']);
		$form = $obj->getForm($donnee = array(), false, true);
		$form->display();
    break;
    
    // Pour supprimer un téléchargement
    case "del_downloads":
        global $xoopsModule;
		$obj =& $downloads_Handler->get($_REQUEST['downloads_lid']);
		if (isset($_REQUEST['ok']) && $_REQUEST['ok'] == 1) {
			if (!$GLOBALS['xoopsSecurity']->check()) {
				redirect_header('downloads.php', 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
			}
            $downloads_lid = $_REQUEST['downloads_lid'];
            // permet d'extraire le nom du fichier
            $urlfile = substr_replace($obj->getVar('url'),'',0,strlen($uploadurl_downloads));
			if ($downloads_Handler->delete($obj)) {
                // permet de donner le chemin du fichier
                $urlfile = $uploaddir_downloads . $urlfile;
                // si le fichier est sur le serveur il es détruit
                if (is_file($urlfile)){		
					chmod($urlfile, 0777);
					unlink($urlfile);
				}
                // supression des votes
                $criteria = new CriteriaCompo();
                $criteria->add(new Criteria('lid', $downloads_lid));
                $downloads_votedata = $downloadsvotedata_Handler->getall( $criteria );
                foreach (array_keys($downloads_votedata) as $i) {
                    $objvotedata =& $downloadsvotedata_Handler->get($downloads_votedata[$i]->getVar('ratingid'));
                    $downloadsvotedata_Handler->delete($objvotedata) or $objvotedata->getHtmlErrors();
                }
                // supression des rapports de fichier brisé
                $criteria = new CriteriaCompo();
                $criteria->add(new Criteria('lid', $downloads_lid));
                $downloads_broken = $downloadsbroken_Handler->getall( $criteria );
                foreach (array_keys($downloads_broken) as $i) {
                    $objbroken =& $downloadsbroken_Handler->get($downloads_broken[$i]->getVar('reportid'));
                    $downloadsbroken_Handler->delete($objbroken ) or $objbroken ->getHtmlErrors();
                }
                // supression des data des champs sup.
                $criteria = new CriteriaCompo();
                $criteria->add(new Criteria('lid', $downloads_lid));
                $downloads_fielddata = $downloadsfielddata_Handler->getall( $criteria );
                foreach (array_keys($downloads_fielddata) as $i) {
                    $objfielddata =& $downloadsfielddata_Handler->get($downloads_fielddata[$i]->getVar('iddata'));
                    $downloadsfielddata_Handler->delete($objfielddata) or $objvfielddata->getHtmlErrors();
                }
                // supression des commentaires
                xoops_comment_delete($xoopsModule->getVar('mid'), $downloads_lid);
                //supression des tags
                if (($xoopsModuleConfig['usetag'] == 1) and (is_dir('../../tag'))){
                    $tag_handler = xoops_getmodulehandler('link', 'tag');
                    $criteria = new CriteriaCompo();
                    $criteria->add(new Criteria('tag_itemid', $downloads_lid));
                    $downloads_tags = $tag_handler->getall( $criteria );
                    foreach (array_keys($downloads_tags) as $i) {
                        $objtags =& $tag_handler->get($downloads_tags[$i]->getVar('tl_id'));
                        $tag_handler->delete($objtags) or $objtags->getHtmlErrors();
                    }
                }
				redirect_header('downloads.php', 1, _AM_TDMDOWNLOADS_REDIRECT_DELOK);
			} else {
				echo $obj->getHtmlErrors();
			}
		} else {
			xoops_confirm(array('ok' => 1, 'downloads_lid' => $_REQUEST['downloads_lid'], 'op' => 'del_downloads'), $_SERVER['REQUEST_URI'], sprintf(_AM_TDMDOWNLOADS_FORMSUREDEL, $obj->getVar('title')) . '<br><br>' . _AM_TDMDOWNLOADS_FORMWITHFILE . ' <b><a href="' . $obj->getVar('url') . '">' . $obj->getVar('url') . '</a></b><br>');
		}
    break;
    
    // Pour voir les détails du téléchargement
    case "view_downloads":
        //information du téléchargement
		$view_downloads = $downloads_Handler->get($_REQUEST['downloads_lid']);
        //catégorie
        $view_categorie = $downloadscat_Handler->get($view_downloads->getVar('cid'));       
        // sortie des informations
		$downloads_title = $view_downloads->getVar('title');
        $downloads_description = $view_downloads->getVar('description');
        //permet d'enlever [pagebreak] du texte
        $downloads_description = str_replace('[pagebreak]','',$downloads_description);
        // pour référentiel de module
        $downloads_description = str_replace('[block]','<h2><u>' . _MD_TDMDOWNLOADS_SUP_BLOCS . '</u></h2>',$downloads_description);
        $downloads_description = str_replace('[notes]','<h2><u>' . _MD_TDMDOWNLOADS_SUP_NOTES . '</u></h2>',$downloads_description);
        $downloads_description = str_replace('[evolutions]','<h2><u>' . _MD_TDMDOWNLOADS_SUP_EVOLUTIONS . '</u></h2>',$downloads_description);
        $downloads_description = str_replace('[infos]','<h2><u>' . _MD_TDMDOWNLOADS_SUP_INFOS . '</u></h2>',$downloads_description);
        $downloads_description = str_replace('[changelog]','<h2><u>' . _MD_TDMDOWNLOADS_SUP_CHANGELOG . '</u></h2>',$downloads_description);
        $downloads_description = str_replace('[backoffice]','<h2><u>' . _MD_TDMDOWNLOADS_SUP_BACKOFFICE . '</u></h2>',$downloads_description);
        $downloads_description = str_replace('[frontoffice]','<h2><u>' . _MD_TDMDOWNLOADS_SUP_FRONTOFFICE . '</u></h2>',$downloads_description);

        // affichages des informations du téléchargement
		echo '<table width="100%" cellspacing="1" class="outer">';
		echo '<tr>';
		echo '<th align="center" colspan="2">' . $downloads_title . '</th>';
		echo '</tr>';
        echo '<tr class="even">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMFILE . ' </td>';
		echo '<td><a href="../visit.php?cid=' . $view_downloads->getVar('cid') . '&lid=' . $_REQUEST['downloads_lid'] . '"><img src="../images/icon/download.png" alt="Download ' . $downloads_title . '" title="Download ' . $downloads_title . '"></a></td>';
		echo '</tr>';
        echo '<tr class="odd">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMCAT . ' </td>';
		echo '<td>' . $view_categorie->getVar('title') . ' <a href="category.php?op=view_cat&downloadscat_cid=' . $view_downloads->getVar('cid') . '"><img src="../images/icon/view_mini.png" alt="' . _AM_TDMDOWNLOADS_FORMDISPLAY . '" title="' . _AM_TDMDOWNLOADS_FORMDISPLAY . '"></a></td>';
		echo '</tr>';
        $criteria = new CriteriaCompo();
        $criteria->setSort('weight ASC, title');
        $criteria->setOrder('ASC');
        $criteria->add(new Criteria('status', 1));
        $downloads_field = $downloadsfield_Handler->getall($criteria);
        $class = 'odd';
        foreach (array_keys($downloads_field) as $i) {
            $class = ($class == 'even') ? 'odd' : 'even';
            echo '<tr class="' . $class . '">';
            if ($downloads_field[$i]->getVar('status_def') == 1){
                if ($downloads_field[$i]->getVar('fid') == 1){
                    //page d'accueil
                    echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMHOMEPAGE . ' </td>';
                    echo '<td><a href="' . $view_downloads->getVar('homepage') . '">' . $view_downloads->getVar('homepage') . '</a></td>';
                }
                if ($downloads_field[$i]->getVar('fid') == 2){
                    //version
                    echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMVERSION . ' </td>';
                    echo '<td>' . $view_downloads->getVar('version') . '</td>';
                }
                if ($downloads_field[$i]->getVar('fid') == 3){
                    //taille du fichier
                    echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMSIZE . ' </td>';
                    echo '<td>' . trans_size($view_downloads->getVar('size')) . '</td>';
                }
                if ($downloads_field[$i]->getVar('fid') == 4){
                    //plateforme
                    echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMPLATFORM . ' </td>';
                    echo '<td>' . $view_downloads->getVar('platform') . '</td>';
                }
            }else{
                $contenu = '';
                echo '<td width="30%">' . $downloads_field[$i]->getVar('title') . ' </td>';
                $criteria = new CriteriaCompo();
                $criteria->add(new Criteria('lid', $_REQUEST['downloads_lid']));
                $criteria->add(new Criteria('fid', $downloads_field[$i]->getVar('fid')));
                $downloadsfielddata = $downloadsfielddata_Handler->getall($criteria);
                foreach (array_keys($downloadsfielddata) as $j) {
                    $contenu = $downloadsfielddata[$j]->getVar('data');
                }                    
                echo '<td>' . $contenu . '</td>';
            }
            echo '</tr>';
        }
        $class = ($class == 'even') ? 'odd' : 'even';
		echo '<tr class="' . $class . '">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMTEXT . ' </td>';
		echo '<td>' . $downloads_description . '</td>';
		echo '</tr>';
        // tags
        if (($xoopsModuleConfig['usetag'] == 1) and (is_dir('../../tag'))){
            require_once XOOPS_ROOT_PATH.'/modules/tag/include/tagbar.php';
            $tags_array = tagBar($_REQUEST['downloads_lid'], 0);
            if (!empty($tags_array)){
                $tags = '';
                foreach (array_keys($tags_array['tags']) as $i) {
                    $tags .= $tags_array['delimiter'] . ' ' . $tags_array['tags'][$i] . ' ';
                }
                
                $class = ($class == 'even') ? 'odd' : 'even';
                echo '<tr class="' . $class . '">';
                echo '<td width="30%">' . $tags_array['title'] . ' </td>';
                echo '<td>' . $tags . '</td>';
                echo '</tr>';
            }
        }        
        if ( $xoopsModuleConfig['useshots']){
            $class = ($class == 'even') ? 'odd' : 'even';
            echo '<tr class="' . $class . '">';
            echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMIMG . ' </td>';
            echo '<td><img src="' . $uploadurl . $view_downloads->getVar('logourl') . '" alt="" title=""></td>';
            echo '</tr>';
        }      
		$class = ($class == 'even') ? 'odd' : 'even';
		echo '<tr class="' . $class . '">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMDATE . ' </td>';
		echo '<td>' . formatTimestamp($view_downloads->getVar('date')) . '</td>';
		echo '</tr>';        
		$class = ($class == 'even') ? 'odd' : 'even';
		echo '<tr class="' . $class . '">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMPOSTER . ' </td>';
		echo '<td>' . XoopsUser::getUnameFromId($view_downloads->getVar('submitter')) . '</td>';
		echo '</tr>';        
		$class = ($class == 'even') ? 'odd' : 'even';
		echo '<tr class="' . $class . '">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMHITS . ' </td>';
		echo '<td>' . $view_downloads->getVar('hits'). '</td>';
		echo '</tr>';
		$class = ($class == 'even') ? 'odd' : 'even';
		echo '<tr class="' . $class . '">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMRATING . ' </td>';
		echo '<td>' . number_format($view_downloads->getVar('rating'),1) . ' (' . $view_downloads->getVar('votes') . ' ' . _AM_TDMDOWNLOADS_FORMVOTE . ')</td>';
		echo '</tr>';
		$class = ($class == 'even') ? 'odd' : 'even';
		echo '<tr class="' . $class . '">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMCOMMENTS . ' </td>';
		echo '<td>' . $view_downloads->getVar('comments') . ' <a href="../singlefile.php?cid=' . $view_downloads->getVar('cid') . '&lid=' . $_REQUEST['downloads_lid'] . '"><img src="../images/icon/view_mini.png" alt="' . _AM_TDMDOWNLOADS_FORMDISPLAY . '" title="' . _AM_TDMDOWNLOADS_FORMDISPLAY . '"></a></td>';
		echo '</tr>';
		$class = ($class == 'even') ? 'odd' : 'even';
		echo '<tr class="' . $class . '">';
		echo '<td width="30%">' . _AM_TDMDOWNLOADS_FORMACTION . ' </td>';
		echo '<td>';
        echo ($view_downloads->getVar('status') != 0 ? '' : '<a href="downloads.php?op=update_status&downloads_lid=' . $_REQUEST['downloads_lid'] . '"><img src="./../images/icon/renew_mini.gif" border="0" alt="' . _AM_TDMDOWNLOADS_FORMVALID . '" title="' . _AM_TDMDOWNLOADS_FORMVALID . '"></a> ');
        echo '<a href="downloads.php?op=edit_downloads&downloads_lid=' . $_REQUEST['downloads_lid'] . '"><img src="../images/icon/edit_mini.gif" alt="' . _AM_TDMDOWNLOADS_FORMEDIT .
        '" title="' . _AM_TDMDOWNLOADS_FORMEDIT . '"></a> <a href="downloads.php?op=del_downloads&downloads_lid=' . $_REQUEST['downloads_lid'] . '">
        <img src="../images/icon/delete_mini.gif" alt="' . _AM_TDMDOWNLOADS_FORMDEL . '" title="' . _AM_TDMDOWNLOADS_FORMDEL . '"></a></td>';
		echo '</tr>';
		echo '</table>';
		echo '<br>';        
        // Affichage des votes:
        
        // Utilisateur enregistré
        echo '<hr>';
        $criteria = new CriteriaCompo();
        $criteria->add(new Criteria('lid', $_REQUEST['downloads_lid']));
        $criteria->add(new Criteria('ratinguser', 0, '!='));
        $downloadsvotedata_arr = $downloadsvotedata_Handler->getall($criteria);
        $total_vote = $downloadsvotedata_Handler->getCount($criteria);        
        echo '<table width="100%">';
        echo '<tr><td colspan="5"><b>';
        printf(_AM_TDMDOWNLOADS_DOWNLOADS_VOTESUSER, $total_vote);
        echo '</b><br /><br /></td></tr>';
        echo '<tr><td><b>' . _AM_TDMDOWNLOADS_DOWNLOADS_VOTE_USER . '</b></td>' . '<td><b>' . _AM_TDMDOWNLOADS_DOWNLOADS_VOTE_IP . '</b></td>' . '<td align="center"><b>' . _AM_TDMDOWNLOADS_FORMRATING . '</b></td>'
        . '<td><b>' . _AM_TDMDOWNLOADS_FORMDATE . '</b></td>' . '<td align="center"><b>' . _AM_TDMDOWNLOADS_FORMDEL . '</b></td></tr>';
        foreach (array_keys($downloadsvotedata_arr) as $i) {
            echo '<tr>';
            echo '<td>' . XoopsUser::getUnameFromId($downloadsvotedata_arr[$i]->getVar('ratinguser')) . '</td>';
            echo '<td>' . $downloadsvotedata_arr[$i]->getVar('ratinghostname') . '</td>';
            echo '<td align="center">' . $downloadsvotedata_arr[$i]->getVar('rating') . '</td>';
            echo '<td>' . formatTimestamp($downloadsvotedata_arr[$i]->getVar('ratingtimestamp')) . '</td>';
            echo '<td align="center">';
            echo myTextForm('downloads.php?op=del_vote&lid=' . $downloadsvotedata_arr[$i]->getVar('lid') . '&rid=' . $downloadsvotedata_arr[$i]->getVar('ratingid') , 'X');
            echo '</td>';
            echo '</tr>';
        }        
        // Utilisateur anonyme
        $criteria = new CriteriaCompo();
        $criteria->add(new Criteria('lid', $_REQUEST['downloads_lid']));
        $criteria->add(new Criteria('ratinguser', 0));
        $downloadsvotedata_arr = $downloadsvotedata_Handler->getall($criteria);
        $total_vote = $downloadsvotedata_Handler->getCount($criteria);
        echo '<tr><td colspan="5"><br /><b>';
        printf(_AM_TDMDOWNLOADS_DOWNLOADS_VOTESANONYME, $total_vote);
        echo '</b><br /><br /></td></tr>';   
        echo '<tr><td colspan="2"><b>' . _AM_TDMDOWNLOADS_DOWNLOADS_VOTE_IP . '</b></td>' . '<td align="center"><b>' . _AM_TDMDOWNLOADS_FORMRATING . '</b></td>'
        . '<td><b>' . _AM_TDMDOWNLOADS_FORMDATE . '</b></td>' . '<td align="center"><b>' . _AM_TDMDOWNLOADS_FORMDEL . '</b></td></tr>';
        foreach (array_keys($downloadsvotedata_arr) as $i) {
            echo '<tr>';
            echo '<td colspan="2">' . $downloadsvotedata_arr[$i]->getVar('ratinghostname') . '</td>';
            echo '<td align="center">' . $downloadsvotedata_arr[$i]->getVar('rating') . '</td>';
            echo '<td>' . formatTimestamp($downloadsvotedata_arr[$i]->getVar('ratingtimestamp')) . '</td>';
            echo '<td align="center">';
            echo myTextForm('downloads.php?op=del_vote&lid=' . $downloadsvotedata_arr[$i]->getVar('lid') . '&rid=' . $downloadsvotedata_arr[$i]->getVar('ratingid') , 'X');            
            echo '</tr>';
        }
        echo'</table>';
	break;
    
    // permet de suprimmer un vote et de recalculer la note
    case "del_vote":
        $objvotedata =& $downloadsvotedata_Handler->get($_REQUEST['rid']);
        if ($downloadsvotedata_Handler->delete($objvotedata)) {
            $criteria = new CriteriaCompo();
            $criteria->add(new Criteria('lid', $_REQUEST['lid']));
            $downloadsvotedata_arr = $downloadsvotedata_Handler->getall($criteria);
            $total_vote = $downloadsvotedata_Handler->getCount($criteria);
            $obj =& $downloads_Handler->get($_REQUEST['lid']);
            if ($total_vote == 0){
                $obj->setVar('rating', number_format(0, 1));
                $obj->setVar('votes', 0);
                if ($downloads_Handler->insert($obj)) {
                    redirect_header('downloads.php?op=view_downloads&downloads_lid=' . $_REQUEST['lid'], 1, _AM_TDMDOWNLOADS_REDIRECT_DELOK);
                }
            }else{
                $total_rating = 0;
                foreach (array_keys($downloadsvotedata_arr) as $i) {
                    $total_rating += $downloadsvotedata_arr[$i]->getVar('rating');
                }            
                $rating = $total_rating / $total_vote;
                $obj->setVar('rating', number_format($rating, 1));
                $obj->setVar('votes', $total_vote);
                if ($downloads_Handler->insert($obj)) {
                    redirect_header('downloads.php?op=view_downloads&downloads_lid=' . $_REQUEST['lid'], 1, _AM_TDMDOWNLOADS_REDIRECT_DELOK);
                }
            }
            echo $obj->getHtmlErrors();
        }
        echo $objvotedata->getHtmlErrors();
    break;
    
    // Pour sauver un téléchargement
	case "save_downloads":
        global $xoopsDB;
        include_once XOOPS_ROOT_PATH.'/class/uploader.php';
		if (!$GLOBALS['xoopsSecurity']->check()) {
           redirect_header('category.php', 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
        }
        if (isset($_REQUEST['lid'])) {
           $obj =& $downloads_Handler->get($_REQUEST['lid']);
        } else {
           $obj =& $downloads_Handler->create();
        }
        $erreur = false;
        $message_erreur = '';
        $donnee = array();
        $obj->setVar('title', $_POST['title']);        
        $obj->setVar('cid', $_POST['cid']);
        $obj->setVar('homepage', formatURL($_POST['homepage']));
        $obj->setVar('version', $_POST['version']);
        $obj->setVar('size', $_POST['size']);
        if (isset($_POST['platform'])) {
            $obj->setVar('platform', implode('|',$_POST['platform']));
        }
        $obj->setVar('description', $_POST['description']);

		if (!isset($_REQUEST['downloads_modified'])) {			
			$obj->setVar('submitter', !empty($xoopsUser) ? $xoopsUser->getVar('uid') : 0);
            $obj->setVar('date', time());
            $obj->setVar('status', 1);
		}else{
            $obj->setVar('submitter', $_POST["submitter"]);
            if ($_POST["date_update"] == 1){
                $obj->setVar('date', time());
                $obj->setVar('status', 2);
            }else{
                $obj->setVar('status', 1);
            }
        }        
        // erreur si la taille du fichier n'est pas un nombre
        if (intval($_REQUEST['size']) == 0){
            if ($_REQUEST['size'] == '0' || $_REQUEST['size'] == ''){
                $erreur = false;
            }else{
                $erreur = true;
                $message_erreur .= _AM_TDMDOWNLOADS_ERREUR_SIZE . '<br>';
            }
        }
        // erreur si la description est vide
        if (isset($_REQUEST['description'])){
            if ($_REQUEST['description'] == ''){
                $erreur=true;
                $message_erreur .= _AM_TDMDOWNLOADS_ERREUR_NODESCRIPTION . '<br>';
            }
        }
        // erreur si la catégorie est vide
        if (isset($_REQUEST['cid'])){
            if ($_REQUEST['cid'] == 0){
                $erreur = true;
                $message_erreur .= _AM_TDMDOWNLOADS_ERREUR_NOCAT . '<br>';
            }
        }
        // pour enregistrer temporairement les valeur des champs sup
        $criteria = new CriteriaCompo();
        $criteria->setSort('weight ASC, title');
        $criteria->setOrder('ASC');
        $downloads_field = $downloadsfield_Handler->getall($criteria);
        foreach (array_keys($downloads_field) as $i) {
            if ($downloads_field[$i]->getVar('status_def') == 0){
                $nom_champ = 'champ' . $downloads_field[$i]->getVar('fid');
                $donnee[$nom_champ] = $_POST[$nom_champ];
            }       
        }
        // enregistrement temporaire des tags
        if (($xoopsModuleConfig['usetag'] == 1) and (is_dir('../../tag'))){
            $donnee['TAG'] = $_POST['tag'];
        }
        
        if ($erreur == 1){
            echo '<div class="errorMsg" style="text-align: left;">' . $message_erreur . '</div>';        
        }else{
            // Pour le fichier
            if (isset($_POST['xoops_upload_file'][0])){            
                $uploader = new XoopsMediaUploader($uploaddir_downloads, explode('|',$xoopsModuleConfig['mimetype']), $xoopsModuleConfig['maxuploadsize'], null, null);
                if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
                    if ($xoopsModuleConfig['newnamedownload']){
                        $uploader->setPrefix($xoopsModuleConfig['prefixdownloads']) ;
                    }
                    $uploader->fetchMedia($_POST['xoops_upload_file'][0]);
                    if (!$uploader->upload()) {
                        $errors = $uploader->getErrors();
                        redirect_header("javascript:history.go(-1)",3, $errors);
                    } else {
                        $obj->setVar('url', $uploadurl_downloads . $uploader->getSavedFileName());
                    }
                } else {
                    $obj->setVar('url', $_REQUEST['url']);
                }
            }
            // Pour l'image
            if (isset($_POST['xoops_upload_file'][1])){
                $uploader_2 = new XoopsMediaUploader($uploaddir, array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/x-png', 'image/png'), $xoopsModuleConfig['maxuploadsize'], null, null);
                if ($uploader_2->fetchMedia($_POST['xoops_upload_file'][1])) {
                    $uploader_2->setPrefix('downloads_') ;
                    $uploader_2->fetchMedia($_POST['xoops_upload_file'][1]);
                    if (!$uploader_2->upload()) {
                        $errors = $uploader_2->getErrors();
                        redirect_header("javascript:history.go(-1)",3, $errors);
                    } else {
                        $obj->setVar('logourl', $uploader_2->getSavedFileName());
                    }
                } else {
                    $obj->setVar('logourl', $_REQUEST['logo_img']);
                }
            }
            // enregistrement
            if ($downloads_Handler->insert($obj)) {
                if (!isset($_REQUEST['downloads_modified'])) {
                    $lid_dowwnloads = $obj->get_new_enreg();
                }else{
                    $lid_dowwnloads = $_REQUEST['lid'];
                }
                //tags
                if (($xoopsModuleConfig['usetag'] == 1) and (is_dir('../../tag'))){
                    $tag_handler = xoops_getmodulehandler('tag', 'tag');
                    $tag_handler->updateByItem($_POST['tag'], $lid_dowwnloads, $xoopsModule->getVar('dirname'), 0);
                }
                // Récupération des champs supplémentaires:
                $criteria = new CriteriaCompo();
                $criteria->setSort('weight ASC, title');
                $criteria->setOrder('ASC');
                $downloads_field = $downloadsfield_Handler->getall($criteria);
                foreach (array_keys($downloads_field) as $i) {
                    if ($downloads_field[$i]->getVar('status_def') == 0){        
                        $iddata = 'iddata' . $downloads_field[$i]->getVar('fid');
                        if (isset($_REQUEST[$iddata])) {                            
                            if ($_REQUEST[$iddata] == ''){
                                $objdata =& $downloadsfielddata_Handler->create();
                            }else{
                                $objdata =& $downloadsfielddata_Handler->get($_REQUEST[$iddata]);                            
                            }
                        } else {
                            $objdata =& $downloadsfielddata_Handler->create();
                        }
                        $nom_champ = 'champ' . $downloads_field[$i]->getVar('fid');
                        $objdata->setVar('data', $_POST[$nom_champ]);
                        $objdata->setVar('lid', $lid_dowwnloads);
                        $objdata->setVar('fid', $downloads_field[$i]->getVar('fid'));
                        $downloadsfielddata_Handler->insert($objdata) or $objdata->getHtmlErrors();
                    }       
                }
                // pour les notifications uniquement lors d'un nouveau téléchargement
                if (!isset($_REQUEST['downloads_modified'])) {
                    $tags = array();
                    $tags['FILE_NAME'] = $_POST['title'];
                    $tags['FILE_URL'] = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/singlefile.php?cid=' . $_POST['cid'] . '&amp;lid=' . $lid_dowwnloads;
                    $downloadscat_cat = $downloadscat_Handler->get($_POST['cid']);
                    $tags['CATEGORY_NAME'] = $downloadscat_cat->getVar('title');
                    $tags['CATEGORY_URL'] = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewcat.php?cid=' . $_POST['cid'];
                    $notification_handler =& xoops_gethandler('notification');
                    $notification_handler->triggerEvent('global', 0, 'new_file', $tags);
                    $notification_handler->triggerEvent('category', $_POST['cid'], 'new_file', $tags);
                }
                redirect_header('downloads.php?op=liste', 2, _AM_TDMDOWNLOADS_REDIRECT_SAVE);
            }
            echo $obj->getHtmlErrors();
        }
        $form =& $obj->getForm($donnee, true, true);
        $form->display();
	break;
    
    // permet de valider un téléchargement proposé
    case "update_status":
        $obj =& $downloads_Handler->get($_REQUEST['downloads_lid']);
        $obj->setVar('status', 1);
        if ($downloads_Handler->insert($obj)) {
            redirect_header('downloads.php?op=liste&statut_display=0', 1, _AM_TDMDOWNLOADS_REDIRECT_SAVE);
        }        
        echo $obj->getHtmlErrors();
    break;
    
    // permet de valider un téléchargement proposé
    case "lock_status":
        $obj =& $downloads_Handler->get($_REQUEST['downloads_lid']);
        $obj->setVar('status', 0);
        if ($downloads_Handler->insert($obj)) {
            redirect_header('downloads.php?op=liste&statut_display=0', 1, _AM_TDMDOWNLOADS_REDIRECT_SAVE);
        }        
        echo $obj->getHtmlErrors();
    break; 
}
//Affichage de la partie basse de l'administration de Xoops
xoops_cp_footer();
?>